package com.xuecheng.govern.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.govern.gateway.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ShengJinFeng
 * @version V1.0
 * @ClassName LoginFilterTest
 * @Description (登录过滤)
 * @date 2020/3/12 11:45
 * @since V1.0
 */
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private AuthService authService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * @Description
     * 1、从cookie查询用户身份令牌是否存在，不存在则拒绝访问
     * 2、从http header查询jwt令牌是否存在，不存在则拒绝访问
     * 3、从Redis查询user_token令牌是否过期，过期则拒绝访问
     * @author ShengJinFeng
     * @date 2020/3/12
     */
    @Override
    public Object run() throws ZuulException {
        //获取请求对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String accessToken = authService.getTokenFromCookie(request);
        if (StringUtils.isEmpty(accessToken)){
            return accessDenied();//拒绝访问
        }
        //从Redis查询user_token令牌是否过期
        long expire = authService.getExpire(accessToken);
        if (expire<0){
            return accessDenied();//拒绝访问
        }
        //从请求头中获取jwt令牌
        String jwt = authService.getJwkFormHeader(request);
        if (StringUtils.isEmpty(jwt)){
            return accessDenied();//拒绝访问
        }
        return null;
    }

    /**
     * @Description 拒绝访问
     * @author ShengJinFeng
     * @date 2020/3/12
     */
    private Object accessDenied(){
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();
        requestContext.setSendZuulResponse(false);//拒绝访问
        requestContext.setResponseStatusCode(200);//设置响应状态码
        ResponseResult responseResult = new ResponseResult(CommonCode.UNAUTHENTICATED);
        String jsonString = JSON.toJSONString(responseResult);
        requestContext.setResponseBody(jsonString);
        response.setContentType("application/json;charset=utf-8");
        return null;
    }
}
